<template>
    <!-- 商品管理弹出框 -->
    <div>
        <el-dialog :title="isAdd ? '添加商品' : '修改商品'" :visible="isShow" :before-close="offCheck" center @opened="open">
            <el-form :model="goodsInfo" :rules="rules" label-width="100px" class="demo-ruleForm" ref="goodsForm">
                <el-form-item label="上级分类" prop="first_cateid">
                    <el-select v-model="goodsInfo.first_cateid" placeholder="请选择" @change="changeCate(true)">
                        <el-option v-for="item in cateList" :key="item.id" :label="item.catename" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="分类名称" prop="second_cateid">
                    <el-select v-model="goodsInfo.second_cateid" placeholder="请选择">
                        <el-option v-for="item in cateChildren" :key="item.id" :label="item.catename" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" prop="goodsname">
                    <el-input v-model="goodsInfo.goodsname"></el-input>
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="goodsInfo.price"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" prop="market_price">
                    <el-input v-model="goodsInfo.market_price"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <!-- 图片上传组件 -->
                    <el-upload action="#" list-type="picture-card" :on-preview="onPreview" :on-remove="onRemove"
                        :on-change="changeFile" :file-list="fileList" :limit="1" :on-exceed="handleExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <!-- 图片预览组件 -->
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" prop="specsid">
                    <el-select v-model="goodsInfo.specsid" placeholder="请选择" @change="changeSpecs(true)">
                        <el-option v-for="item in specsList" :key="item.id" :label="item.specsname" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格属性" prop="specsattr">
                    <el-select v-model="goodsInfo.specsattr" placeholder="请选择" multiple>
                        <el-option v-for="item in specsChildren" :key="item" :label="item" :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品">
                    <el-radio v-model="goodsInfo.isnew" :label="1">是</el-radio>
                    <el-radio v-model="goodsInfo.isnew" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="是否热卖">
                    <el-radio v-model="goodsInfo.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodsInfo.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="状态">
                    <el-switch v-model="goodsInfo.status" active-color="#13ce66" inactive-color="#ccc" :active-value="1"
                        :inactive-value="2">
                    </el-switch>
                </el-form-item>
                <el-form-item>
                    <div id="editor">

                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="offCheck">取 消</el-button>
                <el-button type="primary" @click="addMenu">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
//引入封装好的接口
import { goodsEdit, goodsAdd, goodsInfo } from "../../request/api";
//引入辅助性函数
import { mapGetters, mapActions } from "vuex";
// 引入富文本编译器
import Editor from "wangeditor"
export default {
    computed: {
        ...mapGetters({
            // 获取商品分类列表
            cateList: "cate/getCateList",
            // 获取商品规格属性列表
            specsList: "specs/getSpecsList"
        })
    },
    // 接受参数
    props: ["isShow", "isAdd"],
    data() {
        return {
            goodsInfo: {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: "",
                description: "",
                specsid: "",
                specsattr: "",
                isnew: 1,
                ishot: 1,
                status: 1
            },
            cateChildren: [],
            specsChildren: [],
            fileList: [],
            dialogVisible: false,
            dialogImageUrl: "",
            rules: {
                first_cateid: [
                    { required: true, message: '请输入一级分类', trigger: 'blur' }
                ],
                second_cateid: [
                    { required: true, message: '请输入二级分类', trigger: 'blur' }
                ],
                goodsname: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' },
                    { min: 2, max: 16, message: '长度在 2 到 16 个字符', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' },
                ],
                market_price: [
                    { required: true, message: '请输入商品市场价格', trigger: 'blur' },
                ],
                specsid: [
                    { required: true, message: '请输入商品规格', trigger: 'blur' },
                ],
                specsattr: [
                    { required: true, message: '请输入规格属性', trigger: 'blur' },
                ]
            },
            Editor: []
        };
    },
    mounted() {
        // 判断商品分类列表是否有值，没有则调用获取行动
        if (this.cateList.length == 0) {
            this.getCateList()
        }
        // 商品规格列表是否有值，没有则调用获取行动
        this.getSpecsList()
    },
    methods: {
        // 获取二级商品分类列表
        changeCate(flag) {
            if (flag) {
                this.goodsInfo.second_cateid = ""
            }
            let idx = this.cateList.findIndex(item => item.id == this.goodsInfo.first_cateid)
            this.cateChildren = this.cateList[idx].children
        },
        // 获取二级商品规格属性列表
        changeSpecs(flag) {
            if (flag) {
                this.goodsInfo.specsattr = ""
            }
            let idx = this.specsList.findIndex(item => item.id == this.goodsInfo.specsid)
            this.specsChildren = this.specsList[idx].attrs
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        // 文件修改时触发
        changeFile(file, filelist) {
            this.goodsInfo.img = file.raw;
        },
        // 图片预览
        onPreview(file) {
            //给预览图片赋值
            this.dialogImageUrl = file.url;
            //打开弹框
            this.dialogVisible = true;
        },
        // 图片删除
        onRemove(file, filelist) {
        },

        ...mapActions({
            // 获取商品列表分类
            getCateList: "cate/getCateList_Action",
            // 获取商品规格属性
            getSpecsList: "specs/specsList_Action",
            // 获取当前页的商品列表
            getGoodsList: "goods/goodsList_Action",
            // 获取商品管理列表总数
            getGoodsCount: "goods/goodsCount_Action"
        }),
        //点击取消
        offCheck() {
            // 子传父
            this.$emit("offCheck", false)
            // 清空表单信息
            this.$refs.goodsForm.resetFields()
            this.goodsInfo = {
                first_cateid: "",
                second_cateid: "",
                goodsname: "",
                price: "",
                market_price: "",
                img: "",
                description: "",
                specsid: "",
                specsattr: "",
                isnew: 1,
                ishot: 1,
                status: 1
            }
            this.cateChildren = []
            this.specsChildren = []
            this.fileList = []
            // 销毁富文本编译器
            this.Editor.destroy()
        },
        // 点击实现数据回显
        getOneGoods(id) {

            // 调用获取一条数据接口
            goodsInfo({ id }).then(res => {
                if (res.code == 200) {
                    this.goodsInfo = res.list;
                    //对图片进行数据回显
                    this.fileList = [{ url: this.goodsInfo.img || "" }]
                    this.goodsInfo.id = id;
                    //针对于规格属性进行结构转化
                    this.goodsInfo.specsattr = this.goodsInfo.specsattr.split(',')
                    //重新调用change事件 目的实现 label的渲染
                    this.changeCate(false);
                    this.changeSpecs(false);
                }
            })
        },
        //点击确定
        addMenu() {
            this.$refs.goodsForm.validate(flag => {
                if (flag) {
                    let specsattr = this.goodsInfo.specsattr.join(",")
                    // 判断是添加还是编辑
                    if (this.isAdd) {
                        //调用添加接口
                        goodsAdd({ ...this.goodsInfo, specsattr, description: this.Editor.txt.html() }).then(res => {
                            this.$message.success(res.msg);
                            this.offCheck()
                            // 重新渲染商品管理总数
                            this.getGoodsCount()
                            // 重新渲染商品管理列表
                            this.getGoodsList()
                        })
                    } else {
                        // 调用编辑接口
                        goodsEdit({ ...this.goodsInfo, specsattr, description: this.Editor.txt.html() }).then(res => {
                            this.$message.success(res.msg);
                            this.offCheck()
                            // 重新渲染商品管理总数
                            this.getGoodsCount()
                            // 重新渲染商品管理列表
                            this.getGoodsList()
                        })
                    }
                } else {
                    this.$message.error("请输入正确的内容");
                }
            })
        },
        // 加载富文本编译器
        open() {
            this.Editor = new Editor("#editor")
            this.Editor.create()
            this.Editor.txt.html(this.goodsInfo.description)
        }
    }
};
</script>

<style scoped lang="less">
</style>
